
"""
This class holds the Bing class which is used to create and execute queries
against Bing.
"""

import urllib, httplib2
try: import json
except ImportError: import simplejson as json
	
############## Constants #####################

API_VERSION = '2.0'
JSON_ENDPOINT = 'http://api.search.live.net/json.aspx'
MAX_PAGE_SIZE = 50
MAX_RESULTS = 1000

WEB_SOURCE_TYPE = 'Web'
IMAGE_SOURCE_TYPE = 'Image'
NEWS_SOURCE_TYPE = 'News'
SPELL_SOURCE_TYPE = 'Spell'
RELATED_SOURCE_TYPE = 'RelatedSearch'
PHONEBOOK_SOURCE_TYPE = 'Phonebook'
ANSWERS_SOURCE_TYPE = 'InstanceAnswer'

class BingSearch(object):
    def __init__(self, app_id):
        self.app_id = app_id
    
    def search(self, query, count, offset, source_type=None, api_version=None, extra_params=None,**kwargs):
        print "*************** SEARCH **************"
        kwargs.update({
            'AppId':    self.app_id,
            'Version':  api_version or API_VERSION,
            'Query':    query,
            'Sources':  source_type or DEFAULT_SOURCE_TYPE,
            'Web.Count': count,
            'Web.Offset': offset
        })
        
        if extra_params:
            kwargs.update(extra_params)
        
        query_string = urllib.urlencode(kwargs)
        response, contents = httplib2.Http().request(JSON_ENDPOINT + '?' + query_string)
        return json.loads(contents)

    def search_web(self, query, count,offset):
        return self.search(query, count, offset, source_type=WEB_SOURCE_TYPE)
